package cn.itcast.controller;

import cn.itcast.service.token.PanoramicUserTokenService;
import cn.itcast.service.token.UserTokenState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * @Author: zhaojie
 * @Date: Created in 13:34 2018/8/13
 * @Description: 前后端分离生成token
 */
@RestController
public class TokenController {
    @Value("${jwt.expire.time}")
    private String expireTime;

    @Autowired
    @Qualifier("userTokenService")
    PanoramicUserTokenService userTokenService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @RequestMapping(value = "/token", method = RequestMethod.POST)
    public ResponseEntity<?> createAuthenticationToken(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpServletResponse response
    ) {
        try {
            String jws = userTokenService.generateToken(username, expireTime);
            return ResponseEntity.ok(new UserTokenState(jws, Integer.valueOf(expireTime)));
        } catch (Exception e) {
            return ResponseEntity.ok(new UserTokenState());
        }
    }
}
